package cn.edu.csust.coursecard.service.impl;

import cn.edu.csust.coursecard.dao.entity.Notice;
import cn.edu.csust.coursecard.common.CodeEnum;
import cn.edu.csust.coursecard.common.RedisKeyEnum;
import cn.edu.csust.coursecard.common.ReturnData;
import cn.edu.csust.coursecard.dao.NoticeMapper;
import cn.edu.csust.coursecard.exception.BaseException;
import cn.edu.csust.coursecard.service.NoticeService;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

import static java.lang.Thread.sleep;


/**
 * @author 许大人
 */
@Service("noticeService")
@CacheConfig(cacheNames = RedisKeyEnum.NOTICE_CACHE_NAME)
public class NoticeServiceImpl implements NoticeService {
    @Resource
    NoticeMapper noticeMapper;

    @Override
    @Cacheable(key = "'legacy'+'-'+#userId")
    public List<Notice> getByUserIdLegacy(Integer userId) {
        return noticeMapper.selectGlobalAndUser(userId);
    }

    @Override
    @Cacheable(key = "#userId")
    public List<Notice> getUser(Integer userId) {
        return noticeMapper.selectByUserId(userId);
    }

    @Override
    @Cacheable(key = "0")
    public List<Notice> getGlobal() {
        return noticeMapper.selectByUserId(0);
    }

    @Override
    public ReturnData getAll() {
        return ReturnData.success(noticeMapper.selectAll());
    }

    @Override
    @Caching(evict = {
            @CacheEvict(value = RedisKeyEnum.NOTICE_CACHE_NAME, key = "#notice.userId"),
            @CacheEvict(value = RedisKeyEnum.NOTICE_CACHE_NAME, key = "'0'"),
    })
    public ReturnData addNotice(Notice notice) {
        notice.setCreateTime(new Date());
        notice.setUpdateTime(new Date());
        notice.setIsValid((byte) 1);
        int row = noticeMapper.insertSelective(notice);
        if (row != 1) {
            throw new BaseException(CodeEnum.REQUEST_FAILED.getCode(), "通知添加失败！");
        }
        return ReturnData.success();
    }

    @Override
    @CacheEvict(value = RedisKeyEnum.NOTICE_CACHE_NAME)
    public ReturnData deleteById(Integer id) {
        int row = noticeMapper.deleteByPrimaryKey(id);
        if (row != 1) {
            throw new BaseException(CodeEnum.REQUEST_FAILED.getCode(), "通知删除失败！");
        }
        return ReturnData.success();
    }

    @Override
    @CacheEvict(value = RedisKeyEnum.NOTICE_CACHE_NAME)
    public ReturnData deleteAll() {
        noticeMapper.deleteAll();
        return ReturnData.success();
    }
}
